package com.kedou.sdk.ui.fragment;

import android.app.Activity;
import android.os.Build;
import android.os.Bundle;
import android.text.TextUtils;
import android.text.format.Formatter;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.TextView;

import androidx.annotation.Nullable;

import com.kedou.sdk.core.HttpEngineApi;
import com.kedou.sdk.core.HttpEngineConduits;
import com.kedou.sdk.download.OnDownloadListener;
import com.kedou.sdk.download.VersionUpdateDownloader;
import com.kedou.sdk.params.bean.VersionInfo;
import com.kedou.sdk.ui.assist.OnFinishActivityListener;
import com.kedou.sdk.utils.CommonUtils;
import com.kedou.sdk.utils.WL;

import java.io.File;

public class DownloadDialogFragment extends BaseDialogFragment implements View.OnClickListener, OnDownloadListener {

    private static final String TAG = DownloadDialogFragment.class.getSimpleName();
    private static final String BUNDLE_KEY = "executeLogin";

    private Button mVersionUpdateCancel;
    private Button mVersionUpdateConfirm;
    private View mVersionUpdateSplitView;
    private TextView mVersionUpdateMessage;
    private ProgressBar mVersionUpdateProgressBar;

    private VersionInfo newVersionInfo;
    private long mCurrentDownloadId;

    public static DownloadDialogFragment newInstance() {
        DownloadDialogFragment fragment = new DownloadDialogFragment();
        Bundle bundle = new Bundle();
        bundle.putBoolean(BUNDLE_KEY, false);
        fragment.setArguments(bundle);
        return fragment;
    }

    private void setExecuteLoginProcess(boolean loginEnable){
        Bundle bundle = getArguments();
        bundle.putBoolean(BUNDLE_KEY, loginEnable);
        setArguments(bundle);
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        HttpEngineConduits conduits = HttpEngineApi.getInstance().getEngineConduits();
        newVersionInfo = conduits.readVersionInfo();
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        super.onCreateView(inflater, container, savedInstanceState);
        View contentView = doInflateContentView(inflater, container, getLayoutIdentifier("hnssn_fragment_version_update"));

        mVersionUpdateCancel = contentView.findViewById(getViewIdentifier("fragment_version_update_cancel"));
        mVersionUpdateConfirm = contentView.findViewById(getViewIdentifier("fragment_version_update_confirm"));
        mVersionUpdateSplitView = contentView.findViewById(getViewIdentifier("fragment_version_update_split"));
        mVersionUpdateMessage = contentView.findViewById(getViewIdentifier("fragment_version_update_message"));
        mVersionUpdateProgressBar = contentView.findViewById(getViewIdentifier("fragment_version_update_progressbar"));

        mVersionUpdateCancel.setOnClickListener(this);
        mVersionUpdateConfirm.setOnClickListener(this);

        String versionUpdateMessage = newVersionInfo.getVersionDesc();
        if (TextUtils.isEmpty(versionUpdateMessage)) {
            versionUpdateMessage = getString(getStringIdentifier("hnssn_version_update_message"));
        }
        mVersionUpdateMessage.setText(versionUpdateMessage);
        setCancelButtonViewVisibility(!CommonUtils.isForceUpdateVersion());

        return contentView;
    }

    private void setCancelButtonViewVisibility(boolean visible) {
        mVersionUpdateCancel.setVisibility(visible ? View.VISIBLE : View.GONE);
        mVersionUpdateSplitView.setVisibility(visible ? View.VISIBLE : View.GONE);
    }

    @Override
    public void onResume() {
        super.onResume();
        VersionUpdateDownloader.getImpl().addOnDownloadListener(this);
    }

    @Override
    public void onPause() {
        super.onPause();
        VersionUpdateDownloader.getImpl().removeOnDownloadListener(this);
    }

    @Override
    public void onClick(View view) {
        if (view == mVersionUpdateCancel) {
            doFinishFragment(true);
            return;
        }

        if (view == mVersionUpdateConfirm) {
            VersionUpdateDownloader versionUpdateManager = VersionUpdateDownloader.getImpl();

            File storageFile = versionUpdateManager.randomMakeDownloadStorageFile(String.valueOf(newVersionInfo.getVersionCode()));
            mCurrentDownloadId = versionUpdateManager.startVersionDownloadTask(newVersionInfo.getUrl(), storageFile, false);
            mVersionUpdateConfirm.setEnabled(mCurrentDownloadId <= 0);

            if (!CommonUtils.isForceUpdateVersion() && !CommonUtils.existsDownloadedVersion()) {
                doFinishFragment(true);
            }
        }
    }

    private OnFinishActivityListener getOnFinishActivityListener() {
        if (!isNullContext()) {
            Activity activity = getActivity();
            if (activity instanceof OnFinishActivityListener) {
                return (OnFinishActivityListener) activity;
            }
        }
        return null;
    }

    private void doFinishFragment(boolean loginEnable) {
        OnFinishActivityListener listener = getOnFinishActivityListener();
        if (listener != null) {
            setExecuteLoginProcess(loginEnable);
            listener.doFinishActivity(this);
        }
    }

    @Override
    public void onDownloadProgress(long downloadId, long updateSize, long totalSize) {
        if(!isResumed() || mCurrentDownloadId != downloadId){
            return;
        }

        if (totalSize < 1 || updateSize < 1) {
            mVersionUpdateProgressBar.setProgress(0);
            mVersionUpdateConfirm.setText(getString(getStringIdentifier("hnssn_version_update_pending")));
            return;
        }

        float progress = (float) updateSize / (float) totalSize * 100f;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            mVersionUpdateProgressBar.setProgress((int) Math.max(progress, 1.0f), true);
        } else {
            mVersionUpdateProgressBar.setProgress((int) Math.max(progress, 1.0f));
        }

        StringBuilder builder = new StringBuilder();
        builder.append(Formatter.formatFileSize(getContext(), updateSize));
        builder.append("/");
        builder.append(Formatter.formatFileSize(getContext(), totalSize));

        mVersionUpdateConfirm.setText(builder.toString());
    }

    @Override
    public void onDownloadCompleted(long downloadId, File file) {
        if(isResumed() && mCurrentDownloadId == downloadId){
            WL.i(TAG, "onVersionUpdateCompleted ============> ");
            mVersionUpdateProgressBar.setProgress(100);
            mVersionUpdateConfirm.setText(getString(getStringIdentifier("hnssn_version_update_completed")));

            doFinishFragment(false);

            VersionUpdateDownloader.getImpl().startVersionInstallTask(file);
        }
    }

    @Override
    public void onDownloadError(long downloadId) {
        if(isResumed() && mCurrentDownloadId == downloadId){
            WL.i(TAG, "onVersionUpdateError ============> ");
            mVersionUpdateConfirm.setEnabled(true);
            mVersionUpdateProgressBar.setProgress(0);
            mVersionUpdateConfirm.setText(getString(getStringIdentifier("hnssn_version_update_confirm")));
        }
    }
}
